define([
	"UtilDir/util",
	"UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
	"Date","DateCN", "css!DateCss",
	"EasyUI","EasyUI-lang"
    ],function(Util, Tool, SelectOrg, SearchBlock){

    var sysPath =  getServer() + "/static/app/fxpg/fxEconomicLossProbabilityComputeT";

    var fxEconomyLossProbabilityComputeFormHtml = sysPath + "/views/fxEconomicLossProbabilityComputeTForm.html";
	var getFxEconomyLossProbabilityComputeController = function(){
		return getServer() + "/fxEconomyLossProbabilityComputes";
	};

	/**
	 * 页面初始化
	 */
	var init = function(){
        initSearchBlock();
        queryBtnBind();
		annualSpanSelectFrom();
		initProvinceSelect("山东省", "日照市", "岚山区");//"北京市", "北京市", "海淀区"   "山东省", "日照市", "岚山区"
		//createFxEconomyLossProbabilityComputeGrid();
	};
	var initProvinceSelect = function (Province, City, Area) {
		var html = "";
		$("#citySelect").append(html);
		$("#areaSelect").append(html);
		$.ajax({
			url: getServer() + "/divisions/root/subdivisions",
			contentType: "application/json",
			type: "get",
			success: function (data) {
				$.each(data, function (idx, item) {
					if (item.divisionName == Province) {
						debugger;
						var divisionId = item.divisionId;
						var htmlCity = '';
						if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
							$("#citySelect").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
							$('#citySelect').val(City);
							var htmlArea = '';
							$.ajax({
								url: getServer() + "/divisions/" + divisionId + "/subdivisions",
								contentType: "application/json",
								type: "get",
								success: function (data) {
									$.each(data, function (idx, item) {
										htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
									});
									$("#areaSelect").append(htmlArea);
									$('#areaSelect').val(Area);
									// 列表
									//createFxEconomyLossMiddleGrid();
									createFxEconomyLossProbabilityComputeGrid();
								}
							});

						} else {
							$.ajax({
								url: getServer() + "/divisions/" + divisionId + "/subdivisions",
								contentType: "application/json",
								type: "get",
								success: function (data) {
									debugger;
									$.each(data, function (idx, item) {
										if (item.divisionName == City) {
											var divisionId = item.divisionId;
											var htmlArea = '';
											$.ajax({
												url: getServer() + "/divisions/" + divisionId + "/subdivisions",
												contentType: "application/json",
												type: "get",
												success: function (data) {
													$.each(data, function (idx, item) {
														htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
													});
													$("#areaSelect").append(htmlArea);
													$('#areaSelect').val(Area);
													createFxEconomyLossProbabilityComputeGrid();
												}
											});
										}
										htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
									});
									$("#citySelect").append(htmlCity);
									$('#citySelect').val(City);
								}
							});
						}
					}
					html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
				});
				$("#provinceSelect").append(html);
				$('#provinceSelect').val(Province);
			}
		});
		$("#provinceSelect").change(function () {
			var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#citySelect option").remove();
			$("#citySelect").append(html);
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
				$("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
				return;
			}
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#citySelect").append(html);
				}
			});
		});
		$("#citySelect").change(function () {
			if ($(this).val() == "") return;
			var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#areaSelect").append(html);
				}
			});
		});
	};

	var annualSpanSelectFrom = function () {
		$.ajax({
			url: getFxEconomyLossProbabilityComputeController() + "/getValidDictItemsByDictCode/" + "annualSpan",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("annualSpanSelect");
				//mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	}

	var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
	};
	var queryBtnBind = function(){
        $("#btnSearch").click(function () {
            createFxEconomyLossProbabilityComputeGrid();
        });
        $("#btnReset").click(function () {
        	var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
			$("#citySelect").append(html);
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
            initProvinceSelect("山东省", "日照市", "岚山区");
		});
	};
	var createFxEconomyLossProbabilityComputeGrid= function() {
		var T = $("#annualSpanSelect").val() || "1";
        $("#fxEconomyLossProbabilityComputeGrid").datagrid({
            url:getFxEconomyLossProbabilityComputeController() + "/getFxEconomyLossProbabilityComputes",
			method:"GET",
            fitColumns: true,
            autoRowHeight: false,
            columns:[[
				{
					field:'province',
					title:'省',
					width:'15%',
					align:'center',
				},
				{
					field:'city',
					title:'市',
					width:'15%',
					align:'center',
				},
				{
					field:'area',
					title:'区（县）',
					width:'15%',
					align:'center',
				},
				{
					field:'damageDegree',
					title:'破坏程度',
					width:'15%',
					align:'center',
					formatter: function (value) {
						//console.log(arguments[1]);
						if (value == "0") {
							return '基本完好';
						} else if (value == "1") {
							return '轻微破坏';
						} else if (value == "2") {
							return '中等破坏';
						} else if (value == "3") {
							return '严重破坏';
						} else if (value == "4") {
							return '完全破坏';
						}
					}
				},
				{
					field:'correctedProbability',
					title:'概率值-修正值(年跨度)',
					width:'13%',
					align:'center',
					formatter:function(value,rowData,rowIndex){
						return (1 - Math.pow((1 - rowData.correctedProbability), parseInt(T))).toFixed(4);
						//return '<a href="#" onclick="_editFxEconomyLossProbabilityCompute(\'' + rowData.id + '\');"> '+rowData.correctedProbability+' </a> '
					}
				},
				{
					field:'economicLoss',
					title:'经济损失-计算（万元）',
					width:'14%',
					align:'center',
				},
				{
					field:'correctedExpectation',
					title:'期望',
					width:'14%',
					align:'center',
					formatter:function(value,rowData,rowIndex){
						var rowsData = $("#fxEconomyLossProbabilityComputeGrid").datagrid('getData').rows, economicLossExpectation = 0;
						var t_expectation = 0;
						//console.log(rowData);
						for (let i = 0; i < rowsData.length; i++) {
							t_expectation = 1 - Math.pow((1 - rowsData[i].correctedProbability), parseInt(T))
							economicLossExpectation += t_expectation * rowsData[i].economicLoss;
						}
						$("#fxEconomyLossProbabilityComputeGrid").datagrid('getRows')[rowIndex]["correctedExpectation"] = economicLossExpectation;//合并单元格
						return economicLossExpectation.toFixed(4);
						//return '<a href="#" onclick="_editFxEconomyLossProbabilityCompute(\'' + rowData.id + '\');"> '+rowData.correctedExpectation+' </a> '
					}
				},
            ]],
            toolbar: [/*{
                iconCls: 'fa fa-plus-circle',
                text:"添加",
                handler: function(){
                    addFxEconomyLossProbabilityCompute();
                }
            }, {
				iconCls: 'fa fa-plus-circle',
				text: "模板",
				handler: function () {
					//downloadTemplate();
					alert("功能暂未实现");
				}
			}, */{
				iconCls: 'fa fa-upload',
				text: "导入",
				handler: function () {
					importForm();
					// alert("功能暂未实现");
				}
			}, {
				iconCls: 'fa fa-download',
				text: "导出",
				handler: function () {
					exportForm();
					// alert("功能暂未实现");
				}
			}/*, {
                iconCls: 'fa fa-trash-o',
                text:"删除",
                handler: function(){
                    deleteFxEconomyLossProbabilityCompute();
                }
            }*/],
            queryParams:{
                province: $("#provinceSelect").val(),
                city: $("#citySelect").val(),
                area: $("#areaSelect").val(),
            },
			onLoadSuccess: function (data) {
				//垂直合并单元格
				mergeCells("fxEconomyLossProbabilityComputeGrid", "province,city,area,correctedExpectation");
			},
            /*pagination: true,
            pageSize: 10*/
        });
    };
	$.extend($.fn.datagrid.methods, {
		editCell: function (jq, param) {
			return jq.each(function () {
				var opts = $(this).datagrid('options');
				var fields = $(this).datagrid('getColumnFields', true).concat(
					$(this).datagrid('getColumnFields'));
				for (var i = 0; i < fields.length; i++) {
					var col = $(this).datagrid('getColumnOption', fields[i]);
					col.editor1 = col.editor;
					if (fields[i] != param.field) {
						col.editor = null;
					}
				}
				$(this).datagrid('beginEdit', param.index);
				for (var i = 0; i < fields.length; i++) {
					var col = $(this).datagrid('getColumnOption', fields[i]);
					col.editor = col.editor1;
				}
			});
		}
	});
	/*导入*/
	var importForm = function () {
		// 模板下载
		$("#uploadModal").modal();
		$("#uploadModal").on("shown.bs.modal", function () {
			var url = getServer() + "/excel/经济损失风险评估-概率性损失区划模板.xlsx";
			$("#downloadZwExcelTemplate").attr("href", url);
		});

		$('#uploadButton').off("click");
		$("#uploadButton").on("click", function () {
			var uploadinput = document.getElementById("uploadFile");
			if (uploadinput.value == "") {
				Util.alert("上传前请先选择文件!");
				return;
			}
			var formData = new FormData();
			formData.append("file", uploadinput.files[0]);
			$.ajax({
				url: getFxEconomyLossProbabilityComputeController() + "/import",
				data: formData,
				processData: false, //因为data值是FormData对象，不需要对数据做处理。
				contentType: false,
				type: "POST",
				success: function (data) {
					$('#uploadModal').modal('hide');
					uploadinput.value = null;
					Util.alert(data);
				}
			});
		});
	};
	/**
	 * 导出
	 */
	var exportForm = function () {
		let province = $("#provinceSelect").val();
		let city = $("#citySelect").val();
		let area = $("#areaSelect").val();
		window.location.href = getFxEconomyLossProbabilityComputeController() + "/export?province=" + province + "&city="
			+ city + "&area=" + area;
	};
	function mergeCells(tableID, colList) {
		var colArray = colList.split(",");
		var tTable = $("#" + tableID);
		var tableRows = tTable.datagrid("getRows");
		var tableRowCnts = tableRows.length;
		var rowspan;
		var preTxt = "";
		var curTxt = "";
		for (j = colArray.length - 1; j >= 0; j--) {
			preTxt = "";
			rowspan = 1;
			for (i = 0; i <= tableRowCnts; i++) {
				if (i == tableRowCnts) {
					curTxt = "";
				} else {
					curTxt = tableRows[i][colArray[j]];
				}
				if (preTxt == curTxt) {
					rowspan += 1;
				} else {
					tTable.datagrid("mergeCells", {
						index: i - rowspan,
						field: colArray[j],//合并字段
						rowspan: rowspan,
						colspan: null
					});
					rowspan = 1;
				}
				preTxt = curTxt;
			}
		}
	};
	var formValidator = function(){
		$("#fxEconomyLossProbabilityComputeTForm").validate({
			rules : {
				fitedProbability : {
					required : true,
				},
				correctedProbability : {
					required : true,
				},
			},
			messages : {
				fitedProbability : {
					required : "拟合概率计算值(p)不允许为空!",
				},
				correctedProbability : {
					required : "概率-修正值不允许为空!",
				},
			}
		});
	};
	var getFxEconomyLossProbabilityCompute = function(id){
		$.ajax({
			url: getFxEconomyLossProbabilityComputeController() + "/"+id,
			type: "get",
			success: function (data) {
				Tool.deserialize("fxEconomicLossProbabilityComputeTForm", data);
			}
		});
	};

	var addFxEconomyLossProbabilityCompute = function () {
		var slidebar = Util.slidebar({
			url: fxEconomyLossProbabilityComputeFormHtml,
			width: "580px",
			cache: false,
			close : true,
			afterLoad: function () {
				formValidator();
				$("#saveBtn").on("click", function () {
					if($("#fxEconomyLossProbabilityComputeForm").valid()){
						var data = Tool.serialize("fxEconomicLossProbabilityComputeForm");
						$.ajax({
							url: getFxEconomyLossProbabilityComputeController() ,
                            contentType:"application/json",
							data: JSON.stringify(data),
							type: "post",
							success: function (data) {
								Util.alert(data.message);
								slidebar.close();
                                createFxEconomyLossProbabilityComputeGrid();
							}
						});
					}
				});
			}
		});
	};
	window._editFxEconomyLossProbabilityCompute = function(fxEconomyLossProbabilityComputeId) {
		var slidebar = Util.slidebar({
			url: fxEconomyLossProbabilityComputeFormHtml,
			width: "580px",
			cache: false,
			close : true,
			afterLoad: function () {
				formValidator();
				getFxEconomyLossProbabilityCompute(fxEconomyLossProbabilityComputeId);
				$("#saveBtn").on("click", function () {
					if($("#fxEconomicLossProbabilityComputeTForm").valid()){
						var data = Tool.serialize("fxEconomicLossProbabilityComputeTForm");
						$.ajax({
							url: getFxEconomyLossProbabilityComputeController(),
                            contentType:"application/json",
                            data: JSON.stringify(data),
							type: "put",
							success: function (data) {
								Util.alert(data.message);
								slidebar.close();
								createFxEconomyLossProbabilityComputeGrid();
							}
						});
					}
				});
			}
		});
	};
	var deleteFxEconomyLossProbabilityCompute = function() {
		var rows = $("#fxEconomyLossProbabilityComputeGrid").datagrid("getSelections");
		if (rows == null || rows.length == 0) {
			Util.alert("请选择一行数据!");
			return;
		}
		Util.confirm("是否要删除选中的数据?", function() {
			var ids = "";
			$.each(rows, function(i, row){
				ids += row.id + ",";

			});
			ids = ids.substr(0,ids.length - 1);
			$.ajax({
				url: getFxEconomyLossProbabilityComputeController() ,
				data: {
					ids : ids
				},
				type: "delete",
				success: function (data) {
					createFxEconomyLossProbabilityComputeGrid();
				}
			});
		}, function() {
			return;
		});

	};

	return {
		init:init
	};
});
